package com.study.simplefactory.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName: MyBeanFactory
 * @Description:
 * @Details:
 * @Author: 郑港旭
 * @Create: 2021-11-12 09:55
 **/
public class MyBeanFactory {
    private static final Map<String, String> beanProperties = new HashMap<>();

    static{
        InputStream inputStream = MyBeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            Enumeration<String> names = (Enumeration<String>) properties.propertyNames();
            while(names.hasMoreElements()){
                String key = names.nextElement();
                String value = properties.getProperty(key);
                beanProperties.put(key, value);
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                assert inputStream != null;
                inputStream.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public Object getBean(String name){
        String value = beanProperties.get(name);
        if(value != null){
            try {
                return Class.forName(value).newInstance();
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        return null;
    }


}
